﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Repository;

namespace Dispatcher.LogicalModels
{
    class DayTable
    {
        public DayTable(DateTime date, ModelContainer modelContainer, List<Place> places)
        {
            Date = date;
            Places = places;
            DayEvents = new Dictionary<Place, List<Event>>();
            var from = date.Date;
            var to = from.AddDays(1);
            foreach (var place in places)
            {
                var placeId = place.Id;
                var dayEvents =
                    modelContainer.EventSet.Where(e => e.Place.Id == placeId && from < e.StartTime && e.StartTime < to).ToList();

                dayEvents.Sort((x, y) =>
                                   {
                                       if (x.StartTime > y.StartTime)
                                       {
                                           return +1;
                                       }

                                       if (x.StartTime < y.StartTime)
                                       {
                                           return -1;
                                       }

                                       return 0;
                                   });
                var minTime = date.Add(new TimeSpan(8, 0, 0));
                var maxTime = date.Add(new TimeSpan(22, 0, 0));
                var fromTime = minTime;
                var toTime = minTime;

                for (var i = 0; i < dayEvents.Count; i++)
                {
                    var e1 = dayEvents[i];
                    fromTime = e1.StartTime;
                    if (fromTime>toTime)
                    {
                        dayEvents.Insert(i, new Event {StartTime = toTime, EndTime = fromTime});
                    }

                    toTime = e1.EndTime;
      
                }

                if (toTime < maxTime)
                {
                    dayEvents.Add(new Event { StartTime = toTime, EndTime = maxTime });
                }

                DayEvents.Add(place, dayEvents);
            }
        }

        public DateTime Date { get; set; }

        public List<Place> Places { get; set; }

        public Dictionary<Place, List<Event>> DayEvents { get; set; } 
    }
}
